package cn.stylefeng.guns.modular.system.service.impl;

import cn.stylefeng.guns.modular.system.model.GameUser;
import cn.stylefeng.guns.modular.system.model.ScoreLevel;
import cn.stylefeng.guns.modular.system.dao.ScoreLevelMapper;
import cn.stylefeng.guns.modular.system.service.IGameUserService;
import cn.stylefeng.guns.modular.system.service.IScoreLevelService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.nineshadow.games.Enum.GameTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liyong
 * @since 2019-11-28
 */
@Service
public class ScoreLevelServiceImpl extends ServiceImpl<ScoreLevelMapper, ScoreLevel> implements IScoreLevelService {
    @Autowired
    private IGameUserService gameUserService;

    @Override
    public Map<String, Object> getUserLevel(Integer userId, Integer gameType) throws Exception{
        Map<String, Object> map = new HashMap<>();
        GameUser gameUser = gameUserService.selectById(userId);
        BigDecimal score = GameTypeEnum.XXL.getType() == gameType ? gameUser.getScore() : gameUser.getMcScore();
        List<ScoreLevel> scoreLevels = selectList(new EntityWrapper<>());
        ScoreLevel scoreLevel = scoreLevels.stream().map(item -> {
            if (item.getMaxScore() == null) {
                item.setMaxScore(BigDecimal.valueOf(Integer.MAX_VALUE));
            }
            return item;
        }).filter(item -> item.getMaxScore().subtract(score).compareTo(BigDecimal.ZERO) > 0 && item.getMinScore().subtract(score).compareTo(BigDecimal.ZERO) <= 0)
                .findFirst().get();
        Assert.notNull(scoreLevel,"获取玩家等级信息失败");
        BigDecimal ratio = score.subtract(scoreLevel.getMinScore()).divide(scoreLevel.getMaxScore().subtract(scoreLevel.getMinScore()), 2, BigDecimal.ROUND_HALF_UP);
        map.put("level", scoreLevel.getLevel());
        map.put("ratio", ratio.doubleValue());
        return map;
    }
}
